package com.lagou.service;

import com.lagou.handler.UserServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.stereotype.Service;

@Service("userService")
public class UserServiceImpl implements UserService {

    public String sayHello(String msg) {
        System.out.println("调用成功--参数 "+msg);
        return "调用成功--参数 "+ msg;
    }

    //hostName:ip地址  port:端口号
    public static void startServer(String hostName,int port) throws InterruptedException {

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //这里使用json序列化
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
//                        pipeline.addLast(new StringEncoder());
//                        pipeline.addLast(new JsonObjectDecoder());
                        pipeline.addLast(new UserServerHandler());

                    }
                });
        serverBootstrap.bind(hostName,port).sync();
        // 将服务注册至zookeeper
        ZkClient zkClient = new ZkClient("127.0.0.1:2181");
        if(!zkClient.exists("/zdy-rpc")){
            zkClient.createPersistent("/zdy-rpc"); //首先创建持久父节点
        }

        // 在父节点下创建当前服务的临时节点
        zkClient.createEphemeral("/zdy-rpc/" + hostName + ":" +port);

    }

}
